package service

import (
	"LogisticsPort/model"
	"LogisticsPort/sql"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"net/http"

	"strconv"
)

func SellerList(c *gin.Context) {
	sql.DBHandle(c, sql.GET, func(context *gin.Context, db *gorm.DB) interface{} {
		var list []model.Seller
		db.Find(&list)
		return list
	})
}

func SalesList(c *gin.Context) {
	sql.DBHandle(c, sql.GET, func(context *gin.Context, db *gorm.DB) interface{} {
		var list []model.GoodsSales
		code := c.Query("code")
		name := c.Query("name")
		area := c.Query("area")
		start := c.Query("startTime")
		end := c.Query("endTime")
		index := c.Query("pageIndex")
		size := c.Query("pageSize")
		pageIndex, indexErr := strconv.Atoi(index)
		pageSize, sizeError := strconv.Atoi(size)
		if code != "" {
			db = db.Where("code = ?", code)
		}
		if name != "" {
			db = db.Where("name = ?", name)
		}
		if area != "" {
			db = db.Where("area = ?", area)
		}
		if start != "" {
			db = db.Where("date >= ? ", start+" 00:00:00")
		}
		if end != "" {
			db = db.Where("date <= ? ", end+" 23:59:59")
		}
		if indexErr == nil && sizeError == nil {
			db = db.Offset((pageIndex - 1) * pageSize).Limit(pageSize)
		}
		db.Find(&list)
		return list
	})
}

func CompanySalesList(c *gin.Context) {
	sql.DBHandle(c, sql.GET, func(context *gin.Context, db *gorm.DB) interface{} {
		account := c.Query("collection_account")
		amount := c.Query("collection_amount")
		start := c.Query("startTime")
		end := c.Query("endTime")
		index := c.Query("pageIndex")
		size := c.Query("pageSize")
		pageIndex, indexErr := strconv.Atoi(index)
		pageSize, sizeError := strconv.Atoi(size)
		if account != "" {
			db = db.Where("collection_account = ?", account)
		}
		if amount != "" {
			db = db.Where("collection_amount = ?", amount)
		}
		if start != "" {
			db = db.Where("date >= ? ", start+" 00:00:00")
		}
		if end != "" {
			db = db.Where("date <= ? ", end+" 23:59:59")
		}
		if indexErr == nil && sizeError == nil {
			db = db.Offset((pageIndex - 1) * pageSize).Limit(pageSize)
		}
		var list []model.CompanySalesRecord
		db.
			Model(&model.CompanySalesRecord{}).
			Preload("CarInfo").
			Preload("ProductSalesRecord", func(d *gorm.DB) *gorm.DB {
				//d.Where("id = ?", 12)
				return d
			}).
			Preload("Customer").
			Preload("ProductSalesRecord.InventoryList").
			Find(&list)

		var companySalesResults []model.CompanySalesResult
		for _, record := range list {
			var productSalesResults []model.ProductSalesResult
			for _, salesRecord := range record.ProductSalesRecord {
				if len(salesRecord.InventoryList) != 0 {
					goodsSales := model.ProductSalesResult{
						Id: salesRecord.ID,
						//ProductUnit:   salesRecord.InventoryList[0].ProductUnit,   //产品单位
						SalesNumber:   salesRecord.SalesNumber,                    //销售数量
						SalesWeight:   salesRecord.SalesWeight,                    //销售数量
						SalesPrice:    salesRecord.SalesPrice,                     //销售单价
						Specification: salesRecord.InventoryList[0].Specification, //规格
						FactoryNo:     salesRecord.InventoryList[0].FactoryNo,     //厂号
						ProductName:   salesRecord.InventoryList[0].ProductName,   //品名
					}
					productSalesResults = append(productSalesResults, goodsSales)
				}
			}
			var name = ""
			var phone = ""
			if len(record.Customer) != 0 {
				name = record.Customer[0].Name
				phone = record.Customer[0].PhoneOne
			}
			data := model.CompanySalesResult{
				Id:                 record.ID,
				ProductType:        record.ProductType,
				Customer:           name,
				CustomerPhone:      phone,
				Date:               record.Date,
				Seller:             record.Seller,
				SalesArea:          record.CarInfo[0].SalesArea,
				ProductSalesResult: productSalesResults,
			}
			companySalesResults = append(companySalesResults, data)
		}
		if db.Error != nil {

		}
		return companySalesResults
	})
}
func CompanySalesAdd(c *gin.Context) {
	companySalesEdit(c, sql.ADD)
}

/*func SalesReconciliation(c *gin.Context) {
	sql.DBHandle(c, "", func(context *gin.Context, db *gorm.DB) interface{} {
		var bank model.BankFlow
		bankId := c.Query("bankId")
		db.Where("id = ?", bankId).First(&bank)
		if bank.ID == 0 {
			return nil
		}
		var record model.CompanySalesRecord
		salesId := c.Query("salesId")
		db.Where("id = ?", salesId).Find(&record)
		if record.ID == 0 {
			return nil
		}
		if record.PendingPayment > bank.AccountBalance {
			record.PendingPayment = record.PendingPayment - bank.AccountBalance
			bank.AccountBalance = 0
		} else if record.PendingPayment < bank.AccountBalance {
			bank.AccountBalance = bank.AccountBalance - record.PendingPayment
			record.PendingPayment = 0
		} else {
			record.PendingPayment = 0
			bank.AccountBalance = 0
		}
		err := db.Model(&record).Association("BankFlow").Append(&bank)
		if err != nil {
			fmt.Println("err:", err)
		}
		return nil
	})
}*/

func CompanySalesDelete(c *gin.Context) {
	sql.DBHandle(c, "", func(context *gin.Context, db *gorm.DB) interface{} {
		id := c.Query("id")
		db.Where("id = ?", id).
			Delete(&model.CompanySalesRecord{})
		if db.RowsAffected == 0 {
			return sql.ErrorDelete(c)
		}
		return nil
	})
}

func companySalesEdit(c *gin.Context, text string) {
	sql.DBHandle(c, text, func(context *gin.Context, db *gorm.DB) interface{} {
		var salesRecord model.CompanySalesRecord
		if err := c.Bind(&salesRecord); err != nil {
			return sql.RequestError(c)
		}
		if salesRecord.CustomerName == "" {
			return sql.ParamError(c, "请输入客户信息")
		}
		//销售的商品
		var productSalesRecord []model.ProductSalesRecord
		data := c.PostForm("productSalesRecord")
		err := json.Unmarshal([]byte(data), &productSalesRecord)
		if err != nil {
			return sql.RequestError(c)
		}
		//客户信息，没有该客户直接新增，有不新增
		salesRecord.Customer = []model.Customer{
			{Model: gorm.Model{ID: salesRecord.CustomerId}, Name: salesRecord.CustomerName, PhoneOne: salesRecord.CustomerPhone},
		}
		//车辆信息
		salesRecord.CarInfo = []model.CarInfo{
			{Id: salesRecord.ID, SalesArea: salesRecord.CarPlate, PlateNumber: salesRecord.CarPlate},
		}
		//销售数量、销售重量、商品id、商品名称、库存数量、库存重量
		for i, product := range productSalesRecord {
			productSalesRecord[i].CustomerId = salesRecord.CustomerId
			productSalesRecord[i].Date = salesRecord.Date
			/*updateDB := db.Model(&model.Inventory{}).
				Where("id = ? AND product_number >= ? AND product_weight >= ?", product.ProductId, product.SalesNumber, product.SalesWeight).
				Updates(map[string]interface{}{"product_number": gorm.Expr("product_number - ?", product.SalesNumber),
					"product_weight": gorm.Expr("product_weight - ?", product.SalesWeight)})
			if updateDB.RowsAffected == 0 {
				c.JSON(http.StatusOK, &model.BaseJsonBean{
					Code: 200, Message: "库存不足",
				})
				return nil
			}*/
			salesRecord.TotalPrice += product.TotalPrice
		}
		//商品信息
		salesRecord.ProductSalesRecord = productSalesRecord

		if text == sql.ADD {
			db = db.Create(&salesRecord)
		} else if text == sql.UPDATE {
			db = db.Updates(&salesRecord)
		}
		if db.RowsAffected > 0 {
			return salesRecord
		}
		c.JSON(http.StatusOK, &model.BaseJsonBean{
			Code: 200, Message: text + "失败",
		})
		return nil
	})
}

func GoodsSalesList(c *gin.Context) {
	sql.DBHandle(c, sql.GET, func(context *gin.Context, db *gorm.DB) interface{} {
		account := c.Query("collection_account")
		amount := c.Query("collection_amount")
		start := c.Query("startTime")
		end := c.Query("endTime")
		index := c.Query("pageIndex")
		size := c.Query("pageSize")
		pageIndex, indexErr := strconv.Atoi(index)
		pageSize, sizeError := strconv.Atoi(size)
		if account != "" {
			db = db.Where("collection_account = ?", account)
		}
		if amount != "" {
			db = db.Where("collection_amount = ?", amount)
		}
		if start != "" {
			db = db.Where("date >= ? ", start+" 00:00:00")
		}
		if end != "" {
			db = db.Where("date <= ? ", end+" 23:59:59")
		}
		if indexErr == nil && sizeError == nil {
			db = db.Offset((pageIndex - 1) * pageSize).Limit(pageSize)
		}
		/*var result []model.GoodsSalesResult
		db.
			Model(&model.ProductSalesRecord{}).
			Select("goods_sales_record.id," +
				"goods_sales_record.product_unit," +
				"goods_sales_record.sales_number," +
				"goods_sales_record.unit_price," +
				"goods_sales_record.date," +
				"inventory.factory_no," +
				"inventory.product_name").
			Joins("left join inventory on inventory.id = goods_sales_record.product_id").
			Scan(&result)
		return result*/
		var record []model.ProductSalesRecord
		db.Preload("InventoryList").Find(&record)
		return record
	})
}

func GoodsSalesDetail(c *gin.Context) {
	sql.DBHandle(c, sql.GET, func(context *gin.Context, db *gorm.DB) interface{} {
		account := c.Query("collection_account")
		amount := c.Query("collection_amount")
		start := c.Query("startTime")
		end := c.Query("endTime")
		index := c.Query("pageIndex")
		size := c.Query("pageSize")
		pageIndex, indexErr := strconv.Atoi(index)
		pageSize, sizeError := strconv.Atoi(size)
		if account != "" {
			db = db.Where("collection_account = ?", account)
		}
		if amount != "" {
			db = db.Where("collection_amount = ?", amount)
		}
		if start != "" {
			db = db.Where("date >= ? ", start+" 00:00:00")
		}
		if end != "" {
			db = db.Where("date <= ? ", end+" 23:59:59")
		}
		if indexErr == nil && sizeError == nil {
			db = db.Offset((pageIndex - 1) * pageSize).Limit(pageSize)
		}

		/*var result []model.GoodsSalesResult
		db.
			Model(&model.ProductSalesRecord{}).
			Select("goods_sales_record.id," +
				"goods_sales_record.product_unit," +
				"goods_sales_record.sales_number," +
				"goods_sales_record.unit_price," +
				"goods_sales_record.date," +
				"inventory.factory_no," +
				"inventory.product_name").
			Joins("left join inventory on inventory.id = goods_sales_record.product_id").
			Scan(&result)
		return result*/
		var record []model.ProductSalesRecord
		db.Preload("InventoryList").Find(&record)
		return record
	})
}

func GoodsSalesAdd(c *gin.Context) {
	goodsSalesEdit(sql.ADD, c)
}

func goodsSalesEdit(text string, c *gin.Context) {
	sql.DBHandle(c, text, func(context *gin.Context, db *gorm.DB) interface{} {
		var form model.ProductSalesRecord
		if err := c.Bind(&form); err != nil {
			c.JSON(http.StatusInternalServerError, model.BaseJsonBean{Code: 500, Message: "系统服务异常"})
			return nil
		}
		if form.SalesPrice == 0 {
			return sql.ParamError(c, "产品不能为空")
		} else if form.SalesNumber == 0 {
			return sql.ParamError(c, "产品数量不能为空")
		}
		/*db.Create(&model.ProductSalesRecord{
			SalesNumber: 15,
			UnitPrice:   355,
			InventoryList: []model.Inventory{{
				FactoryNo:   "15289",
				ProductName: "猪手",
			}},
		})*/
		/*if text == sql.ADD {
			db = db.Create(&form)
		} else if text == sql.UPDATE {
			db = db.Updates(&form)
		}*/
		if db.RowsAffected > 0 {
			return form
		}
		c.JSON(http.StatusOK, &model.BaseJsonBean{
			Code: 200, Message: text + "失败",
		})
		return nil
	})
}
